package test;

import java.awt.Component;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.util.List;

import obj.Edge;
import util.Util;

public class CarTestRunnable implements Runnable {

	private CarTest car;

	private Component component;

	public static final int DELAY = 100;

	public CarTestRunnable(CarTest aCar, Component aComponent) {
		car = aCar;
		component = aComponent;
	}

	@Override
	public void run() {
		try {

			while (!car.currentPosition.equals(pathEndPoint)) {
				Point2D.Double point = getNextPosition(car);
				car.move(point);
				component.repaint();
				Thread.sleep(DELAY);
			}

		} catch (InterruptedException e) {
		}

	}

	int edgePosition = 0;
	int count = 0;
	Point2D.Double sPoint = null;
	Point2D.Double pathEndPoint = null;
	Point2D.Double ePoint;

	private Point2D.Double getNextPosition(CarTest c) {
		Point2D.Double nextPosition = null;
		boolean isNewEdge = false;
		if(sPoint != null && sPoint.equals(ePoint)){
			edgePosition++;
			isNewEdge = true;
		}
		if(sPoint != null && sPoint.distance(ePoint) <= 20 && !isNewEdge){
			nextPosition = ePoint;
			sPoint = ePoint;
			return nextPosition;
		}


		List<Edge> edgesList = c.getPath().getEdgesList();
		Point pathStartPoint = new Point(edgesList.get(edgePosition).getStartNode().getxPoint(), edgesList
				.get(edgePosition).getStartNode().getyPoint());
		pathEndPoint = new Point2D.Double(edgesList.get(edgesList.size() - 1).getEndNode().getxPoint(), edgesList
				.get(edgesList.size() - 1).getEndNode().getyPoint());

		Edge e = edgesList.get(edgePosition);

		if (count == 0) {
			sPoint = new Point2D.Double(e.getStartNode().getxDouble(), e.getStartNode().getyDouble());
			ePoint = new Point2D.Double(e.getEndNode().getxDouble(), e.getEndNode().getyDouble());
			c.setCarAngle(Util.getAngle(sPoint, ePoint));
		}

		ePoint = new Point2D.Double(e.getEndNode().getxDouble(), e.getEndNode().getyDouble());
		nextPosition = Util.getNextPoint(sPoint, ePoint, 20);
		c.setCarAngle(Util.getAngle(sPoint, ePoint));
		sPoint = nextPosition;
		count++;
		return nextPosition;
	}

}
